<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="message buffer 是基于stream buffer构建的一种轻量级消息传递方式，因此使用message buffer和使用stream buffer存在相同的限制：只有一个写，并且也只有一个读。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-message buffer">
<meta property="og:url" content="http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="message buffer 是基于stream buffer构建的一种轻量级消息传递方式，因此使用message buffer和使用stream buffer存在相同的限制：只有一个写，并且也只有一个读。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/diff_sb_mb.jpg">
<meta property="og:image" content="http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/length-message.jpg">
<meta property="article:published_time" content="2023-03-10T16:00:00.000Z">
<meta property="article:modified_time" content="2023-03-11T10:02:03.622Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/diff_sb_mb.jpg">


<link rel="canonical" href="http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/","path":"2023/03/11/FreeRTOS-message-buffer/","title":"FreeRTOS-message buffer"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-message buffer | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#message-buffer%E5%A6%82%E4%BD%95%E7%9F%A5%E9%81%93%E6%B6%88%E6%81%AF%E7%9A%84%E8%BE%B9%E7%95%8C%EF%BC%9F"><span class="nav-number">1.</span> <span class="nav-text">message buffer如何知道消息的边界？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#message-buffer%E7%9A%84%E5%BA%94%E7%94%A8"><span class="nav-number">2.</span> <span class="nav-text">message buffer的应用</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-message buffer | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-message buffer
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-03-11 00:00:00" itemprop="dateCreated datePublished" datetime="2023-03-11T00:00:00+08:00">2023-03-11</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.9k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>6 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>
message buffer 是基于stream buffer构建的一种轻量级消息传递方式，因此使用message buffer和使用stream buffer存在相同的限制：只有一个写，并且也只有一个读。
</center>

<span id="more"></span>

<hr>
<p><a href="https://fengxun2017.github.io/2023/02/22/FreeRTOS-stream-buffer/">stream buffer</a>提供了一种轻量级的数据流传递方式，所谓数据流，即数据的收发都是以字节为单位的。例如，<br><code>stream buffer</code>的发送数据API：<code>xStreamBufferSend</code>，当我们需要发送<code>N</code>个字节时，当前<code>buffer</code>空间如果不够写入<code>N</code>字节，该API仍旧会根据当前可用空间来写入尽可能多的字节，并返回最终成功写入的字节数。<br><code>stream buffer</code>的获取数据API：<code>xStreamBufferReceive</code>，当我们尝试最大获取<code>N</code>字节数据时，即使当前Buffer并没有那么多的数据，该API 仍旧会根据当前buffer内的数据量返回尽可能多的数据，并最终返回成功获取到的字节数。</p>
<p>这是因为数据流，是没有数据“边界”的概念，发送时会根据当前可用空间大小尽可能多的发送数据。获取数据时，也是尽可能多的获取数据，能获取多少就获取多少。发送和接收过程可能会在任意一个字节发送&#x2F;接收完成后结束。</p>
<p><code>message buffer</code>是基于<code>stream buffer</code>来实现的。因此使用<code>message buffer</code>的场景中也只能有一个writer（任务或中断服务程序），也只能有一个reader（任务或中断服务程序）<br>与<code>stream buffer</code>相比，<code>message buffer</code>就提供了数据“边界的概念”。其发送&#x2F;获取数据都是以消息为单位的（一个消息的长度可以任意）。例如：<br>对于发送消息API：<code>xMessageBufferSend</code>，同样是发送<code>N</code>个字节，该API 要么是将<code>N</code>字节全部发送成功，要么就一个字节也不发送（buffer内的剩余空间不够完整的存放一个消息），我们称为发送了一个大小为<code>N</code>的“消息”。<br>对于获取消息API：<code>xMessageBufferReceive</code>，每次调用要么获取数据大小为 0（buffer为空，没有消息），要么获取的数据是之前发送的一个大小为<code>N</code>的消息。</p>
<p>对于<code>stream buffer</code>和<code>message buffer</code>的区别，假设我们使用<code>stream buffer</code>的API，发送了两次数据，一次是3字节，一次是4字节。<br>同样的数据量，使用<code>message buffer</code>，一次是发送了一个3字节的消息，一次是发送了一个4字节的消息<br>它们的区别如下图所示：<br><img src="/2023/03/11/FreeRTOS-message-buffer/diff_sb_mb.jpg"></p>
<p>对于<code>stream buffer</code>来说，数据是无边界的，存储在buffer里的就是字节流，对于上图存储在<code>stream buffer</code>中的 7 个字节，<code>stream buffer</code>可以通过一次获取数据API 全部读出来。<br>而对于<code>message buffer</code>来说，其中存储的数据是有边界的，一个是3字节的消息，另一个是4字节的消息。一次调用获取数据API，我们只能获得第一个3字节数据，再次调用一次获取数据API，才能获得剩下的 4 字节数据（<code>message buffer</code>不能通过一个API一次性获取这7字节，因为它们是两个消息）。 </p>
<h4 id="message-buffer如何知道消息的边界？"><a href="#message-buffer如何知道消息的边界？" class="headerlink" title="message buffer如何知道消息的边界？"></a>message buffer如何知道消息的边界？</h4><p><code>message buffer</code>通过向buffer中插入一个<strong>长度字段</strong>，来实现识别消息的边界。<br>例如，当我们向<code>message buffer</code>中发送了一个3字节的消息，一个4字节的消息，<code>message buffer</code> 内部的存储实际为：<br><img src="/2023/03/11/FreeRTOS-message-buffer/length-message.jpg"><br>如此，当获取数据（消息）时，通过第一个长度字段就可以知道后续消息的实际长度，并按该长度读出完整的消息数据。<br>PS：32位处理器上，消息数据前的<strong>长度字段</strong>为 4 字节，不是上图的 1 字节。所以一个10字节的消息，实际占用的空间大小是14字节</p>
<h4 id="message-buffer的应用"><a href="#message-buffer的应用" class="headerlink" title="message buffer的应用"></a>message buffer的应用</h4><p>如果你的应用场景中有一个采集任务，它需要采集多种数据，之后封装成多种消息（每个消息长度不一），并发送给另一个数据处理任务。<br>这种情况下，由于只有一个writer&#x2F;reader，<code>message buffer</code> 可以作为<code>消息队列</code>的替代方案。 与<code>消息队列</code>一样，<code>massage buffer</code>也具有识别消息边界的功能，可以以消息为单位进行写&#x2F;读，但<code>message buffer</code>每个消息的长度可以不一样（消息队列中每个消息长度是一样的，即使一个消息中有用数据实际很少，但占用空间大小是固定的），空间利用率会更高。</p>
<p><code>message buffer</code>的使用和<code>stream buffer</code>的使用方式基本一致：<br>首先需要创建一个<code>message buffer</code>：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">MessageBufferHandle_t <span class="title function_">xMessageBufferCreate</span><span class="params">( <span class="type">size_t</span> xBufferSizeBytes )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xBufferSizeBytes：创建的<code>message buffer</code>所占空间的大小（以字节为单位）</li>
<li>返回值：message buffer的句柄，如果返回NULL，表示创建失败（堆空间不足）。</li>
</ul>
<p>发送数据：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">size_t</span> <span class="title function_">xMessageBufferSend</span><span class="params">( MessageBufferHandle_t xMessageBuffer,</span></span><br><span class="line"><span class="params">                            <span class="type">const</span> <span class="type">void</span> *pvTxData,</span></span><br><span class="line"><span class="params">                            <span class="type">size_t</span> xDataLengthBytes,</span></span><br><span class="line"><span class="params">                            TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xMessageBuffer：message buffer句柄（xMessageBufferCreate 的返回值）。</li>
<li>pvTxData：指向需要发送的消息的地址</li>
<li>xDataLengthBytes：消息长度</li>
<li>xTicksToWait：如果message buffer内空间不够，该值指定阻塞等待多久</li>
<li>返回值：返回xDataLengthBytes 表示成功地将完整消息写入了，返回0 表示写入失败（空间不足）。</li>
</ul>
<p>获取数据：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">size_t</span> <span class="title function_">xMessageBufferReceive</span><span class="params">( MessageBufferHandle_t xMessageBuffer,</span></span><br><span class="line"><span class="params">                            <span class="type">void</span> *pvRxData,</span></span><br><span class="line"><span class="params">                            <span class="type">size_t</span> xBufferLengthBytes,</span></span><br><span class="line"><span class="params">                            TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>xMessageBuffer：message buffer句柄（xMessageBufferCreate 的返回值）</li>
<li>pvTxData：用来存放所获取的消息的地址</li>
<li>xBufferLengthBytes：pvTxData所指向空间的大小</li>
<li>xTicksToWait：获取不到消息时，阻塞等待多久</li>
<li>返回值：本次获取的消息的长度。要么为0，要么是一个完成消息的长度。</li>
</ul>
<p><strong>注意</strong>：如果<code>message buffer</code>中可能存在的最大消息的大小为<code>N</code>，那么调用<code>xMessageBufferReceive</code>获取消息时，<code>pvRxData</code>所指的用来存放获取的消息的空间，其大小<code>xBufferLengthBytes</code>应该大于等于<code>N</code>，否则该消息永远无法从<code>message buffer</code>中取出。</p>
<p>一个简单的使用样例： task_a 向 <code>message buffer</code>写入消息，task_b 从<code>message buffer</code>中读取消息。</p>
<p>任务代码如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 向message buffer中，每次发送一个 3 字节消息和一个 4 字节消息。</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_a</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line"></span><br><span class="line">    MessageBufferHandle_t mbuffer = (MessageBufferHandle_t)pvParameters;</span><br><span class="line">    <span class="type">char</span> data[<span class="number">9</span>] = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>&#125;;</span><br><span class="line">    <span class="type">int</span> send_len = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 发送一个 3 字节的消息。</span></span><br><span class="line">        send_len = xMessageBufferSend(mbuffer, data, <span class="number">3</span>, pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;sent %d bytes!\n&quot;</span>, send_len);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 发送一个 4 字节的消息。</span></span><br><span class="line">        send_len = xMessageBufferSend(mbuffer, data, <span class="number">4</span>, pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;sent %d bytes!\n&quot;</span>, send_len);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 从 message buffer中获取消息</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_b</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    </span><br><span class="line">    MessageBufferHandle_t mbuffer = (MessageBufferHandle_t)pvParameters;</span><br><span class="line">    <span class="type">char</span> data[<span class="number">10</span>];</span><br><span class="line">    <span class="type">int</span> recv_len = <span class="number">0</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        recv_len = xMessageBufferReceive(mbuffer, data, <span class="keyword">sizeof</span>(data), pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;%d bytes received\n&quot;</span>, recv_len);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//delay，让消费变慢</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>main 函数如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;message_buffer.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建一个message buffer，最多可以放 20字节。</span></span><br><span class="line">    MessageBufferHandle_t sbuffer= xMessageBufferCreate(<span class="number">20</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">NULL</span> != sbuffer) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> (pdPASS == xTaskCreate(task_a, <span class="string">&quot;task_a&quot;</span>, <span class="number">100</span>, sbuffer, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">            &amp;&amp; pdPASS == xTaskCreate(task_b, <span class="string">&quot;task_b&quot;</span>, <span class="number">100</span>, sbuffer, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">            </span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">            vTaskStartScheduler();</span><br><span class="line">        &#125; </span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>运行结果如下:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">sent 3 bytes!</span><br><span class="line">sent 4 bytes!</span><br><span class="line">3 bytes received    #用来存放接收消息的data 大小为10，但每次获取的数据仍旧只是一个完整消息的大小（3或4字节）</span><br><span class="line">sent 3 bytes!</span><br><span class="line">sent 0 bytes!       #没空间了，目前message buffer中还有一个4字节消息和一个3字节消息</span><br><span class="line">                    #两个消息实际占用了 7 字节加8字节（两个消息的长度字段）</span><br><span class="line">                    #还剩 5字节，不够4字节的消息+4字节长度，就不会发送，不会像stream buffer一样有多少空间发送多少数据。</span><br><span class="line">4 bytes received</span><br><span class="line">sent 0 bytes!</span><br><span class="line">sent 4 bytes!</span><br><span class="line">sent 0 bytes!</span><br><span class="line">3 bytes received</span><br><span class="line">sent 0 bytes!</span><br><span class="line">sent 3 bytes!</span><br><span class="line">sent 0 bytes!</span><br><span class="line">4 bytes received</span><br><span class="line">sent 0 bytes!</span><br><span class="line">sent 4 bytes!</span><br><span class="line">sent 0 bytes!</span><br></pre></td></tr></table></figure>


<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱






    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/" title="FreeRTOS-message buffer">http://fengxun2017.github.io/2023/03/11/FreeRTOS-message-buffer/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2023/03/07/BleStack-link-states-draft/" rel="prev" title="协议栈——链路层相关概念——笔记草稿">
                  <i class="fa fa-chevron-left"></i> 协议栈——链路层相关概念——笔记草稿
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/03/25/BleStack-hardware-driver/" rel="next" title="实现一个精简的BLE从机协议栈—1—基础概念和硬件驱动实现">
                  实现一个精简的BLE从机协议栈—1—基础概念和硬件驱动实现 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
